<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form :inline="true">
      <el-form-item label="姓名">
        <el-input v-model="q.name" placeholder="请输入姓名" clearable @keyup.enter.native="fetchData" />
      </el-form-item>
      <el-form-item label="账号">
        <el-input v-model="q.username" placeholder="请输入账号" clearable @keyup.enter.native="fetchData" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchData">查询</el-button>
        <el-button type="primary" @click="addUser">新增用户</el-button>
        <el-button @click="batchDeleteUsers">批量删除</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      :data="userList"
      border
      :header-cell-style="{ background: '#fafafa' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="username" label="账号" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="telephone" label="手机" />
      <el-table-column prop="last_login" label="最近登录" />
      <el-table-column label="操作" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="editUser(scope.row)">编辑</el-button>
          <el-button type="text" @click="resetPassword(scope.row)">重置密码</el-button>
          <el-button type="text" @click="singleDeleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="fetchData" />

    <el-drawer :title="userDrawerTitle" :visible.sync="userDrawerShow" direction="rtl" :before-close="handleCloseDrawer">
      <div class="drawer-container-scroll">
        <el-form ref="userForm" :model="userForm" :rules="userFormRules" label-width="90px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="账号" prop="username">
            <el-input v-model="userForm.username" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="userForm.telephone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="userForm.gender">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="userForm.is_active">
              <el-radio :label="true">正常</el-radio>
              <el-radio :label="false">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="角色" prop="role_ids">
            <div class="select-container">
              <el-select v-model="userForm.role_ids" multiple clearable placeholder="请选择角色">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="所属部门" prop="dept_ids">
            <div class="select-container">
              <SelectTree
                ref="treeSelect"
                v-model="userForm.dept_ids"
                :data="deptOptions"
                single-select-emit-array
              />
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="drawer-footer__btn">
          <el-button @click="handleCloseDrawer">取 消</el-button>
          <el-button type="primary" @click="saveSubmit">保 存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import apiUser from '@/api/system/user'
import apiRole from '@/api/system/role'
import apiDept from '@/api/system/dept'
import Pagination from '@/components/Pagination'
import SelectTree from '@/components/SelectTree'
const defaultForm = {
  id: '',
  name: '',
  username: '',
  telephone: '',
  email: '',
  gender: 0,
  is_active: true,
  role_ids: [],
  dept_ids: [],
  depts: [],
  roles: []
}

export default {
  components: { Pagination, SelectTree },
  data() {
    return {
      userList: [],
      roleOptions: [],
      deptOptions: [],
      listLoading: false,
      page: 1,
      limit: 10,
      total: 0,
      q: {
        name: '',
        username: ''
      },
      ids: [],
      userDrawerShow: false,
      userDrawerTitle: '新增用户',
      submitType: 0, // 0:新增 1:编辑
      userForm: defaultForm,
      userFormRules: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        role_ids: [
          { required: true, message: '角色不能为空', trigger: 'blur' }
        ],
        dept_ids: [
          { required: true, message: '部门不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const params = {
        page: this.page,
        limit: this.limit,
        username: this.q.username,
        name: this.q.name
      }
      apiUser.getUserList(params).then(response => {
        this.userList = response.data
        this.total = response.count
      })
      this.listLoading = false
    },
    // 获取部门、角色选项列表
    getRoleAndDeptOptions() {
      apiRole.getRoleOptions().then(response => {
        this.roleOptions = response.data
      })
      apiDept.getDeptOptions().then(response => {
        this.deptOptions = response.data
      })
    },
    addUser() {
      this.getRoleAndDeptOptions()
      this.userDrawerShow = true
      this.userDrawerTitle = '新增用户'
      this.submitType = 0
      this.userForm = Object.assign({}, defaultForm)
    },
    editUser(row) {
      this.getRoleAndDeptOptions()
      this.userDrawerShow = true
      this.userDrawerTitle = '编辑用户'
      this.submitType = 1
      // 把depts的id遍历赋值给dept_ids
      if (row.depts.length > 0) {
        row.dept_ids = row.depts.map(item => item.id)
      }
      // 把roles的id遍历赋值给role_ids
      if (row.roles.length > 0) {
        row.role_ids = row.roles.map(item => item.id)
      }
      this.userForm = Object.assign({}, row)
    },
    async saveSubmit() {
      await this.$refs.userForm.validate(async validate => {
        if (validate) {
          if (this.submitType === 0) {
            await apiUser.createUser(this.userForm).then(response => {
              this.$message.success(response.message || '新增成功')
            }).catch(error => {
              this.$message.error(error.response.data['message'])
            })
          } else {
            await apiUser.updateUser(this.userForm).then(response => {
              this.$message.success(response.message || '编辑成功')
            }).catch(error => {
              this.$message.error(error.response.data['message'])
            })
          }
          this.userDrawerShow = false
          await this.fetchData()
        }
      })
    },
    handleCloseDrawer() {
      this.userDrawerShow = false
    },
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.id)
    },
    async singleDeleteUser(row) {
      const data = [row.id]
      await this.deleteSubmit(data)
    },
    async batchDeleteUsers() {
      if (this.ids.length === 0) {
        this.$message.error('请选择要删除的用户')
        return
      }
      await this.deleteSubmit(this.ids)
    },
    async deleteSubmit(data) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        lockScroll: false,
        type: 'warning'
      }).then(async() => {
        await apiUser.deleteUser(data).then(async response => {
          this.$message.success(response.message || '删除成功')
          await this.fetchData()
        })
      })
    },
    async resetPassword(row) {
      this.$confirm('确定要重置密码？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        lockScroll: false,
        type: 'warning'
      }).then(async() => {
        await apiUser.resetUserPassword(row.id).then(async response => {
          this.$message.success(response.message || '重置成功')
        })
      })
    }
  }
}
</script>
